package cn.car91.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.R.integer;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;
import cn.car91.R;
import cn.car91.activity.MapActivity.MapType;
import cn.car91.adapter.SearchItemsAdapter;
import cn.car91.adapter.SearchItemsAdapter.SearchItemInfo;
import cn.car91.bean.SearchInfo;
import cn.car91.utils.RegexUtil;
import cn.car91.view.HerilyAlertDialog.Builder;
import cn.car91.view.MyListView;
import cn.car91.view.WordWrapView;

import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.util.LogUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

public class RoundActivity extends BaseActivity {

	@ViewInject(R.id.round_list)
	WordWrapView roundListView;
	@ViewInject(R.id.round_search_key)
	AutoCompleteTextView roundSearchKey;
	@ViewInject(R.id.round_history)
	View historyView;
	@ViewInject(R.id.round_histories)
	MyListView historyListView;
	
	private SearchItemsAdapter adapter;
	private final int searchType = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		setContentView(R.layout.activity_round);
		super.onCreate(savedInstanceState);

		initView();

		roundSearchKey
				.setOnEditorActionListener(new AutoCompleteTextView.OnEditorActionListener() {
					@Override
					public boolean onEditorAction(
							TextView AutoCompleteTextView, int arg1,
							KeyEvent arg2) {
						if (arg1 == EditorInfo.IME_ACTION_SEND
								|| arg1 == EditorInfo.IME_ACTION_SEARCH
								|| (arg2 != null && arg2.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
							onSearchClick(AutoCompleteTextView);
							return true;
						}
						return false;
					}
				});

		((TextView) findViewById(R.id.header_text)).setText("周边服务");
	}

	private void initView() {
	    for (int i = 0; i < 9; i++) {
	        if(1==i) {
	            roundListView.addView(createTextView(R.drawable.round_baggreen,getResources().getString(R.string.round_traffic)));
	        }
	        else if(2==i) {
	            roundListView.addView(createTextView(R.drawable.round_bagblue,getResources().getString(R.string.round_oil)));
	        }
	        else if(3==i) {
                roundListView.addView(createTextView(R.drawable.round_bagred,getResources().getString(R.string.round_park)));
            }
	        else if(4==i) {
                roundListView.addView(createTextView(R.drawable.round_bagblue,getResources().getString(R.string.round_repair)));
            }
	        else if(5==i) {
                roundListView.addView(createTextView(R.drawable.round_baggreen,getResources().getString(R.string.round_4s)));
            }
	        else if(6==i) {
                roundListView.addView(createTextView(R.drawable.round_bagred,getResources().getString(R.string.round_wash)));
            }
	        else if(7==i) {
                roundListView.addView(createTextView(R.drawable.round_baggreen,getResources().getString(R.string.round_hotel)));
            }
	        else if(8==i) {
                roundListView.addView(createTextView(R.drawable.round_bagred,getResources().getString(R.string.round_bank)));
            }
	        else if(9==i) {
                roundListView.addView(createTextView(R.drawable.round_bagblue,getResources().getString(R.string.round_restaurant)));
            }
	        
        }
	    
	    adapter = new SearchItemsAdapter(RoundActivity.this, R.layout.view_search_round_item);
	    historyListView.setAdapter(adapter);
	    _initHistories();
	}
	
	private void _initHistories() {
	    try {
            List<SearchInfo> searchInfos = getCar91Application().getDbUtils().findAll(Selector.from(SearchInfo.class).where("type", "=", searchType).orderBy("date",true));
            if(null!=searchInfos && 0<searchInfos.size()) {
                historyView.setVisibility(View.VISIBLE);
                List<SearchItemInfo> searchItemInfos = new ArrayList<SearchItemInfo>();
                for (SearchInfo searchInfo : searchInfos) {
                    SearchItemInfo searchItemInfo = new SearchItemInfo();
                    searchItemInfo.setId(String.valueOf(searchInfo.getId()));
                    searchItemInfo.setName(searchInfo.getKey());
                    searchItemInfo.setOther(searchInfo.getDate().toString());
                    searchItemInfos.add(searchItemInfo);
                }
                adapter.setSearchItems(searchItemInfos);
                adapter.notifyDataSetChanged();
            } else {
                historyView.setVisibility(View.GONE);
            }
        } catch (DbException e) { }
	}
	
	private TextView createTextView(int bgColorResId,String text){
	    TextView textView = (TextView) LayoutInflater.from(this).inflate(R.layout.view_round_item, null);
	    try {
	        textView.setBackgroundResource(bgColorResId);
        } catch (Exception e) { }
	    textView.setText(text);
	    textView.setOnClickListener(onRoundItemClick);
	    return textView;
	}

	private OnClickListener onRoundItemClick = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
            String key = ((TextView)arg0).getText().toString();
		    _saveHistory(key);
			if (getCar91Application().isLocating()) {
				Intent intent = new Intent(RoundActivity.this,
						MapActivity.class);
				intent.putExtra("mapType", MapType.MAP_TYPE_AOUND_ALL);
				intent.putExtra("lon", getCar91Application()
						.getmLocationClient().getLastKnownLocation()
						.getLongitude());
				intent.putExtra("lat", getCar91Application()
						.getmLocationClient().getLastKnownLocation()
						.getLatitude());
				intent.putExtra("zoom", 16);
				intent.putExtra("nearkey", key);
				/*switch (arg0.getId()) {
				case R.id.round_4s:
					intent.putExtra("nearkey", "汽车4S");
					break;
				case R.id.round_bank:
					intent.putExtra("nearkey", "ATM");
					break;
				case R.id.round_hotel:
					intent.putExtra("nearkey", "酒店宾馆");
					break;
				case R.id.round_oil:
					intent.putExtra("nearkey", "加油站");
					break;
				case R.id.round_park:
					intent.putExtra("nearkey", "停车场");
					break;
				case R.id.round_repairshop:
					intent.putExtra("nearkey", "汽车维修");
					break;
				case R.id.round_restaurant:
					intent.putExtra("nearkey", "饭店");
					break;
				case R.id.round_traffic:
					intent.putExtra("nearkey", "交通队");
					break;
				case R.id.round_wash:
					intent.putExtra("nearkey", "洗车");
					break;
				default:
					break;
				}*/
				startActivity(intent);
			} else {
				new Builder(RoundActivity.this).setMessage("正在定位中...").create()
						.show();
			}
		}
	};
	
	private void _saveHistory(String key){
	    try {
            SearchInfo searchInfo = getCar91Application().getDbUtils().findFirst(Selector.from(SearchInfo.class).where("key", "=", key.trim()).and("type", "=", searchType));
            if(null==searchInfo) {
                searchInfo = new SearchInfo();
                searchInfo.setKey(key.trim());
                searchInfo.setType(searchType);
            }
            searchInfo.setDate(new Date());
            getCar91Application().getDbUtils().saveOrUpdate(searchInfo);
            _initHistories();
        } catch (DbException e) { }
	}

	@OnClick(R.id.round_imgBtn_search_submit)
	public void onSearchClick(View view) {
	    String key = roundSearchKey.getEditableText().toString();
	    if(RegexUtil.isNotNull(key)) {
	        _saveHistory(key);
    		if (getCar91Application().isLocating()) {
    			Intent intent = new Intent(RoundActivity.this, MapActivity.class);
    			intent.putExtra("mapType", MapType.MAP_TYPE_AOUND_ALL);
    			intent.putExtra("lon", getCar91Application().getmLocationClient()
    					.getLastKnownLocation().getLongitude());
    			intent.putExtra("lat", getCar91Application().getmLocationClient()
    					.getLastKnownLocation().getLatitude());
    			intent.putExtra("zoom", 16);
    			intent.putExtra("nearkey", key.trim());
    
    			startActivity(intent);
    
    			roundSearchKey.getEditableText().clear();
    		} else {
    			new Builder(RoundActivity.this).setMessage("正在定位中...").create()
    					.show();
    		}
	    } else {
	        
	    }
	}
	
	@OnClick(R.id.round_histories_clear)
	public void onHistoryClear(View view) {
	    try {
            getCar91Application().getDbUtils().delete(SearchInfo.class, WhereBuilder.b("type", "=", searchType));
            _initHistories();
        } catch (DbException e) { }
	}
}
